/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package okhttp3.internal.http;

import static okhttp3.internal.Util.hostHeader;

import java.io.IOException;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.Version;
import okio.GzipSource;
import okio.Okio;

/**负责把用户构造的请求转换为发送给服务器的请求，把服务器返回的响应转换为对用户友好的响应
 * <br/>转换的过程就是添加一些服务端需要的header信息
 * <br/>在Request阶段配置用户信息，并添加一些请求头。在Response阶段，进行gzip解压
 *
 * <br/>这个方法主要是针对Header做了一些处理，这里主要提一下"Accept-Encoding", "gzip"，关于它有以下几点需要注意：
 * <br/>开发者没有添加Accept-Encoding时，自动添加Accept-Encoding: gzip
 * <br/>自动添加Accept-Encoding，会对request，response进行自动解压
 * <br/>手动添加Accept-Encoding，不负责解压缩
 * <br/>自动解压时移除Content-Length，所以上层Java代码想要contentLength时为-1
 * <br/>自动解压时移除 Content-Encoding
 * <br/>自动解压时，如果是分块传输编码，Transfer-Encoding: chunked不受影响
 * Bridges from application code to network code. First it builds a network request from a user
 * request. Then it proceeds to call the network. Finally it builds a user response from the network
 * response.
 */
public final class BridgeInterceptor implements Interceptor {
	private final CookieJar cookieJar;

	public BridgeInterceptor(CookieJar cookieJar) {
		this.cookieJar = cookieJar;
	}

	@Override
	public Response intercept(Chain chain) throws IOException {
		Request userRequest = chain.request();
		// 从用户请求中获取网络请求构建者
		Request.Builder requestBuilder = userRequest.newBuilder();

		RequestBody body = userRequest.body();
		if (body != null) {
			// 进行Header的包装
			MediaType contentType = body.contentType();
			if (contentType != null) {
				requestBuilder.header("Content-Type", contentType.toString());
			}

			long contentLength = body.contentLength();
			if (contentLength != -1) {
				requestBuilder.header("Content-Length", Long.toString(contentLength));
				requestBuilder.removeHeader("Transfer-Encoding");
			} else {
				requestBuilder.header("Transfer-Encoding", "chunked");
				requestBuilder.removeHeader("Content-Length");
			}
		}

		if (userRequest.header("Host") == null) {
			requestBuilder.header("Host", hostHeader(userRequest.url(), false));
		}

		if (userRequest.header("Connection") == null) {
			requestBuilder.header("Connection", "Keep-Alive");
		}

		// If we add an "Accept-Encoding: gzip" header field we're responsible for also
		// decompressing
		// the transfer stream.
		// 如果我们添加一个“Accept-Encoding：gzip”头字段，我们也负责解压缩传输流
		boolean transparentGzip = false;
		if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
			transparentGzip = true;
			requestBuilder.header("Accept-Encoding", "gzip");
		}
		// 创建OkhttpClient配置的cookieJar
		List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
		if (!cookies.isEmpty()) {
			requestBuilder.header("Cookie", cookieHeader(cookies));
		}

		if (userRequest.header("User-Agent") == null) {
			requestBuilder.header("User-Agent", Version.userAgent());
		}
		// 拼接完后执行下一个
		Response networkResponse = chain.proceed(requestBuilder.build());
		// 解析服务器返回的Header，如果没有这个cookie，则不进行解析
		HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

		Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
		// 判断服务器是否支持gzip压缩，如果支持，则将压缩提交给Okio库来处理
		if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
				&& HttpHeaders.hasBody(networkResponse)) {
			GzipSource responseBody = new GzipSource(networkResponse.body().source());
			Headers strippedHeaders = networkResponse.headers().newBuilder().removeAll("Content-Encoding")
					.removeAll("Content-Length").build();
			responseBuilder.headers(strippedHeaders);
			String contentType = networkResponse.header("Content-Type");
			responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
		}

		return responseBuilder.build();
	}

	/**
	 * Returns a 'Cookie' HTTP request header with all cookies, like
	 * {@code a=b; c=d}.
	 */
	private String cookieHeader(List<Cookie> cookies) {
		StringBuilder cookieHeader = new StringBuilder();
		for (int i = 0, size = cookies.size(); i < size; i++) {
			if (i > 0) {
				cookieHeader.append("; ");
			}
			Cookie cookie = cookies.get(i);
			cookieHeader.append(cookie.name()).append('=').append(cookie.value());
		}
		return cookieHeader.toString();
	}
}
